package com.javasea.orm.dynamicDS.controller;

import com.javasea.orm.dynamicDS.DataSourceVo;
import com.javasea.orm.dynamicDS.config.MultitenantDataSource;
import com.javasea.orm.dynamicDS.core.Member;
import com.javasea.orm.dynamicDS.service.MemberService;
import com.javasea.orm.dynamicDS.tenant.TenantContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginController {
	@Autowired
	MemberService memberService;
	@Autowired
	ApplicationContext ctx;
	@RequestMapping(value = "/hello")
	public String hello(){
		System.out.println("Hello");
		return "hi";
	}

	@RequestMapping(value = "/members/{name}/{tenantName}")
	public Member member(@PathVariable("name") String name, @PathVariable("tenantName") String tenantName){
		// 设置租户名称，service方法里面会通过租户名称去查询对应的数据源
		TenantContext.setCurrentTenant(tenantName);
		try {
			Member member = memberService.login(name, "145");
			return member;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.getMessage());
			System.out.println("exception when login");
			return null;
		}

	}

//	@RequestMapping(value = "/members/{name}")
//	public Member member(@PathVariable("name") String name, @RequestHeader("X-TenantID") String tenantName){
//		TenantContext.setCurrentTenant(tenantName);
//		try {
//			Member member = memberService.login(name, "145");
//			return member;
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			System.out.println(e.getMessage());
//			System.out.println("exception when login");
//			return null;
//		}
//
//	}

	@PostMapping("/tenant/register")
	@ResponseBody
	public String tenantRegister(@RequestBody DataSourceVo dataSourceVo) {

		// 在配置数据库中新增数据源信息.我是通过脚本insert的，这里省略
		// insertDataSource()
		// sysProperties 是系统统一取properties 的类
		// 获取context.

		MultitenantDataSource multitenantDataSource = ctx.getBean(MultitenantDataSource.class);
		// 构建新数据源

		DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create()
				//.driverClassName("com.sap.db.jdbc.Driver")
				//com.mysql.jdbc.Driver
				.url(dataSourceVo.getUrl())
				.username(dataSourceVo.getUsername())
				.password(dataSourceVo.getPassword());
		//resolvedDataSources.put(tenantName,dataSourceBuilder.build());

		// 重设并通知，维护的TargetDataSource
		multitenantDataSource.addDataSourceToTargetDataSource(dataSourceVo.getKey(), dataSourceBuilder.build());
		return "success";
	}
}
